import { accountLoginRequest, getUserInfoById, getUserMenuByRoleId } from '@/service/login/login'
import { defineStore } from 'pinia'
import type { IAccount } from '@/types'
import { localCache } from '@/utils/cache'
import router from '@/router'
import { LOGIN_TOKEN, USER_INFO, USER_MENUS } from '@/global/constants'
import { mapMenusToPermissions, mapMenuToRoutes } from '@/utils/map-menu'
import useMainStore from '../main/main'

// 指定 state 的类型
interface ILoginState {
  token: string
  userInfo: any
  userMenus: any
  permissions: string[]
}

const useLoginStore = defineStore('login', {
  state(): ILoginState {
    return {
      token: '',
      userInfo: {},
      userMenus: [],
      permissions: []
    }
  },
  actions: {
    async loginAccountAction(account: IAccount) {
      // 获取 token 信息
      const loginResult = await accountLoginRequest(account)
      const token = loginResult.data.token
      this.token = token
      const id = loginResult.data.id

      // 本地缓存
      localCache.setCache(LOGIN_TOKEN, token)

      // 获取用户的详细信息
      const userInfoResult = await getUserInfoById(id)
      const userInfo = userInfoResult.data
      this.userInfo = userInfo

      // 根据角色请求用户的权限
      const userMenusResult = await getUserMenuByRoleId(this.userInfo.role.id)
      const userMenus = userMenusResult.data
      this.userMenus = userMenus

      // 获取登录用户的所有按钮的权限
      const permissions = mapMenusToPermissions(userMenus)
      this.permissions = permissions

      // 动态添加路由
      const routes = mapMenuToRoutes(userMenus)
      routes.forEach((route) => router.addRoute('main', route))

      // 本地缓存
      localCache.setCache(USER_INFO, userInfo)
      localCache.setCache(USER_MENUS, userMenus)

      // 请求所有的数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()

      // 页面跳转 main 页面
      router.push('/main')
    },
    loadLocalCacheAction() {
      // 用户进行刷新时加载缓存数据
      const token = localCache.getCache(LOGIN_TOKEN)
      const userInfo = localCache.getCache(USER_INFO)
      const userMenus = localCache.getCache(USER_MENUS)

      if (token && userInfo && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus

        // 请求所有的数据
        const mainStore = useMainStore()
        mainStore.fetchEntireDataAction()

        // 获取按钮的权限
        const permissions = mapMenusToPermissions(userMenus)
        this.permissions = permissions

        // 动态添加路由
        const routes = mapMenuToRoutes(userMenus)
        routes.forEach((route) => router.addRoute('main', route))
      }
    }
  }
})

export default useLoginStore
